/*************************************************************************
	> File Name: main.c
	> Author: 
	> Mail: 
	> Created Time: 2018年11月08日 星期四 19时38分56秒
 ************************************************************************/

#include <stdio.h>
#include <stdlib.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <unistd.h>
#include <string.h>
#include <error.h>
#include "../include/QRcode.h"

#define SIZE 1024 //共享内存大小
int main()
{
    //QRcode(); 
    int shmid;
    char *shmaddr;
    struct shmid_ds buf;
    
    int flag = 0;
    int pid;
    
    //创建共享内存
    shmid = shmget(IPC_PRIVATE,SIZE,IPC_CREAT | 0600);
    if(shmid < 0)
    {
        perror("get shm id error!\r\n");
        exit(1);
    }

    pid = fork();
    if(pid == 0)
    {
        char qrCodeBuf[100] = {0};
        shmaddr = (char *)shmat(shmid,NULL,0);
        if(shmaddr == (void*)(-1))
        {
            perror("shmat addr error!\n");
            exit(2);
        }
        QRcode(shmaddr);
        //shmdt(shmaddr);
        return 0;
    }
    else if(pid > 0)
    {
        sleep(3);
        flag = shmctl(shmid,IPC_STAT,&buf);
        if(flag == -1)
        {
            perror("shmctl error!\r\n");
            exit(3);
        }
        printf("shm size = %ld byres \r\n",buf.shm_segsz);
        printf("parent id = %d, shm_cpid = %d\r\n",getpid(),buf.shm_cpid);
        printf("child pid = %d, shm_lpid = %d\r\n",pid,buf.shm_lpid);

        shmaddr = (char *)shmat(shmid,NULL,0);
        if(shmaddr == (void *)(-1))
        {
            perror("shmat error!\r\n");
            exit(4);
        }
        while(1)
        {
            if(strlen(shmaddr) > 1)
            {
                puts(shmaddr);
                memset(shmaddr,0,sizeof(shmaddr));
            }
        }
        //shmdt(shmaddr);
        //shmctl(shmid,IPC_RMID,NULL); //删除
    }
    else
    {
        perror("fork error!\r\n");
        shmctl(shmid,IPC_RMID,NULL);
    }
    return 0;
}
